angular.module('mvcApp.search-products', [
    'ngRoute',
    'ngResource'
]).config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/search-products/:keyword', {
            templateUrl: 'static/views/search-products.html',
            controller: 'SearchProductsCtrl'
        });
}]).controller('SearchProductsCtrl', ['$scope', '$http', '$location', 'User', '$routeParams', 'Shop', 'Category', 'Product',
    function ($scope, $http, $location, User, $routeParams, Shop, Category, Product) {
        $scope.keyword = $routeParams.keyword;
        $scope.products = [];
        $scope.productsPage = 1;
        $scope.productsTotal = 0;
        $scope.pageSize = 10;
        $scope.showPrevPageProducts = function() {
            $scope.productsPage -= 1;
            $scope.loadProducts();
        };
        $scope.showNextPageProducts = function() {
            $scope.productsPage += 1;
            $scope.loadProducts();
        };
        $scope.productsPagesCount = function() {
            return 1 + parseInt(($scope.productsTotal - 1) / $scope.pageSize);
        };
        $scope.loadProducts = function () {
            if ($scope.productsPage < 1) {
                $scope.productsPage = 1;
            }
            Product.searchProducts($scope.keyword, $scope.productsPage, $scope.pageSize)
                .then(function (data) {
                    $scope.products = data.records;
                    $scope.productsTotal = data.total;
                    $scope.$apply();
                }).catch(function (err) {
                    if (err) {
                        alert(err);
                    }
                });
        };
        $scope.showProductPage = function (product) {
            $location.path('/product/' + product.id);
        };
        $scope.loadProducts();
    }]);